/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blue.script;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * @author kelvio
 */
public class ScriptEngineManager {

    private Map<String, Class<? extends ScriptEngine>> scriptEngineMap = new HashMap<>();
    private Map<String, ScriptEngine> scriptEngineCacheMap = new HashMap<>();
    
    private ScriptEngineManager() {
    }

    private static class ScriptEngineManagerHolder {

        private static final ScriptEngineManager INSTANCE = new ScriptEngineManager();
    }
    
    public static ScriptEngineManager getInstance() {
        return ScriptEngineManagerHolder.INSTANCE;
    }

    public void registerScriptEngine(String name, Class<? extends ScriptEngine> scriptEngineClass) {
        this.scriptEngineMap.put(name, scriptEngineClass);
    }

    public Class<? extends ScriptEngine> unregisterScriptEngine(String name) {
        return this.scriptEngineMap.remove(name);
    }

    public <T extends ScriptEngine> T getScriptEngine(String name) {
        if (this.scriptEngineMap.containsKey(name)) {

            if (!this.scriptEngineCacheMap.containsKey(name)) {
                this.scriptEngineCacheMap.put(name, this.createScriptEngine(name));
            }
            return (T) this.scriptEngineCacheMap.get(name);
        }
        throw new RuntimeException("ScriptEngine not found.");
    }

    /**
     *
     * @param name
     * @return
     */
    private ScriptEngine createScriptEngine(String name) {
        try {
            return this.scriptEngineMap.get(name).newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Cannot create a Script engine:" + name);
        }

    }
}
